use core_api::db;
use std::{env, io::Read};
use tauri::{Manager, RunEvent};
mod camera;
mod cmd;
mod download;
mod global;
mod recording;
mod suppa_ftp;
mod version;

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    let (url, init_script) = get_parameters();
    run1(url, init_script);
}

// 初始化脚本
const INIT_SCRIPT: &str = include_str!("init.js");
pub fn run1(url: String, script: String) {
    let version = version::VERSION; //env!("TAURI_APP_VERSION");
    let mut mm = db::MessageManager::new();
    mm.init(true);
    // 保存发送者
    global::write().set_message_manager(Some(mm));

    let mut builder = tauri::Builder::default()
        // .plugin(
        //     tauri_plugin_log::Builder::new()
        //         .timezone_strategy(tauri_plugin_log::TimezoneStrategy::UseLocal)
        //         // log_size > max_file_size 才 rotation_strategy
        //         .rotation_strategy(tauri_plugin_log::RotationStrategy::KeepAll)
        //         .max_file_size(5 * 1024 * 1024 /* bytes */)
        //         .level_for("tao", log::LevelFilter::Error)
        //         .level(log::LevelFilter::Info)
        //         .clear_targets() // 先清除其他目标
        //         .targets([
        //             tauri_plugin_log::Target::new(tauri_plugin_log::TargetKind::Folder {
        //                 path: std::path::PathBuf::from("./logs"),
        //                 file_name: None,
        //             }), //,tauri_plugin_log::Target::new(TargetKind::Stdout),
        //         ])
        //         .build(),
        // )
        .plugin(tauri_plugin_dialog::init())
        .plugin(tauri_plugin_shell::init());

    #[cfg(desktop)]
    {
        builder = builder.plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {
            let _ = app
                .get_webview_window("main")
                .expect("no main window")
                .set_focus();
        }));
    }

    builder
        .setup(move |app| {
            let _window =
                tauri::WebviewWindowBuilder::new(app, "main", tauri::WebviewUrl::App(url.into()))
                    .title(format!("八维考试V{}", version))
                    .initialization_script(script.as_str())
                    .maximized(true)
                    //.use_https_scheme(true)
                    // "decorations": false,
                    // "fullscreen": true,
                    //  "resizable": false,
                    // "alwaysOnTop": true,
                    // "skipTaskbar": true
                    //.devtools(true)
                    //.maximizable(false)
                    //.resizable(false)
                    .build()?;
            //#[cfg(windows)]
            //enable_insecure_content(&window);
            //window.eval("sessionStorage.setItem('message', 'hello from Rust'); console.log('hello from Rust')")?;
            //window.eval("navigator.permissions.query({ name: 'camera' }).then(p => console.log('权限:%o',p));")?;
            // 监听窗口大小变化事件
            // window.on_window_event(|event| {
            //     match event {
            //         tauri::WindowEvent::Resized(size) => {
            //             println!("实时尺寸: {}x{}", size.width, size.height);
            //         },
            //         _ => {}
            //     }
            // });

            // #[cfg(dev)]
            // {
            //     //https://tauri.app/develop/debug/
            //源码实现在tauri-runtime-wry-2.5.0\src
            //    window.open_devtools();
            // }
            // 监听停止录屏事件 ,需要 tauri::Listener
            // app.listen(cmd::EVENT_STOP_RECORDING, |event| {
            //     println!("============EVENT_STOP_RECORDING {:?}", &event.payload());
            // });

            Ok(())
        })
        .invoke_handler(tauri::generate_handler![
            //cmd::check_screen,
            recording::start_recording,
            recording::stop_recording,
            cmd::open_path,
            cmd::upload,
            cmd::get_sysinfo,
            cmd::path_exists,
            recording::validate_checksum,
            cmd::get_status,
            cmd::exec_cmd,
            //cmd::get_camera_img,
            cmd::get_exe_dir,
            download::download_package,
            download::download_file,
            download::unpackage,
            cmd::get_desktop_count,
            cmd::start_hook,
            cmd::check_env,
            cmd::kill_process,
            cmd::check_process,
            cmd::log,
            cmd::log_all_process, //把当前进程列表写入日志文件以逗号分隔
            cmd::get_msg,
            cmd::ack_msg,
            cmd::get_version,
        ])
        /* .on_window_event(|window, event| {
             // 防止摄像头拖动到桌面外部
            if window.label() != "camera" {
                return;
            }
            if let tauri::WindowEvent::Moved(position) = event {
                if let Ok(Some(monitor)) = window.current_monitor() {
                    if let Ok(outer_size) = window.outer_size() {
                        let monitor_size = monitor.size();
                        let new_x = position
                            .x
                            .max(0)
                            .min((monitor_size.width - outer_size.width) as i32);
                        let new_y = position
                            .y
                            .max(0)
                            .min((monitor_size.height - outer_size.height) as i32);
                        if new_x != position.x || new_y != position.y {
                            let _ = window.set_position(tauri::PhysicalPosition::new(new_x, new_y));
                        }
                    }
                }
            }
        }) */
        // .build(tauri::generate_context!())
        // 目录相对于 src-tauri
        .build(tauri::generate_context!("./tauri.conf.json"))
        .expect("初始化程序时出错！")
        .run(|_app, event| match event {
            RunEvent::Ready => {
                //if cfg!(dev)
                // {
                //     let edog_pid = cmd::start_edog();
                //     if edog_pid <= 0 {
                //         app.dialog()
                //             .message("程序不完整!无法启动")
                //             .kind(MessageDialogKind::Error)
                //             .title("提示")
                //             .buttons(MessageDialogButtons::OkCustom("确定".to_string()))
                //             .blocking_show();

                //         cmd::stop_all();
                //         std::process::exit(-1);
                //     }
                // }
                // std::thread::spawn(|| {
                //     let r = recording::detect_camara_mic();
                //     log::info!("detect_camara_mic: {:?}", r);
                // });
            }
            RunEvent::Exit => {
                println!("xxxxxxxx====Exit");
                cmd::stop_all();
            }

            _ => {}
        });
}

fn get_parameters() -> (String, String) {
    // 利用bat 来设置环境变量 获取北京上海宿迁的入口地址
    // 3个bat 北京.bat ,上海.bat,宿迁.bat
    // set SERVICE=beijing
    // set USE_HTTPS=false
    // let mut url = String::from("http://onlyfortest.localhost:8081"); //remote

    let mut protocol = "http";
    let mut host = "172.16.10.111";
    let mut port = "5886";
    if cfg!(debug_assertions) {
        host = "onlyfortest";
        port = "8081";
    }

    let index_page = "";

    if let Ok(service) = env::var("SERVICE") {
        match service.to_ascii_lowercase().as_str() {
            "beijing" => {
                host = "172.16.10.111";
                port = "5886";
            }
            "shanghai" => {
                host = "10.100.57.111";
                port = "5886";
            }
            "suqian" => {
                host = "10.70.100.100";
                port = "5886";
            }
            "test" => {
                host = "onlyfortest";
                port = "8081";
            }
            _ => {}
        };
    }

    if let Ok(https) = env::var("USE_HTTPS") {
        match https.to_ascii_lowercase().as_str() {
            "true" => {
                protocol = "https";
            }
            _ => (),
        };
    }

    let mut url = format!("{}://{}:{}/{}", protocol, host, port, index_page);

    println!("==================Program url: {}", url);
    let script_show_menu = if cfg!(debug_assertions) {
        "document.addEventListener('DOMContentLoaded', function () { console.log('DEBUG model'); initWindowRightMenu(); });"
    } else {
        "document.addEventListener('DOMContentLoaded', function () { console.log('PROD  model');  });"
    };

    //let init_script = String::from(INIT_SCRIPT);
    let init_script = format!(
        "(function(){{ {}\r\n{}\r\n }})()",
        INIT_SCRIPT, script_show_menu
    );
    //log::info!("==================Init script: {}", &init_script);

    let args: Vec<String> = env::args().collect();
    println!("==================Program args: {:?}", args);
    if args.len() == 3 {
        url = args.get(1).unwrap().to_owned();
        //获取初始脚本名称
        let init_script_name = args.get(2).unwrap();
        let mut f = std::fs::File::open(init_script_name).unwrap();
        let mut custom_init_script = String::new();
        f.read_to_string(&mut custom_init_script).unwrap();
        //println!("==================Program args: {:?}", custom_init_script);
        (url, custom_init_script)
    } else {
        (url, init_script)
    }
}
